package easypal.brilliard.world.brilliards.communication.impl;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import easypal.brilliard.util.TraceUtil;
import easypal.brilliard.world.brilliards.communication.CommunicationChannel;
import easypal.brilliard.world.brilliards.communication.CommunicationConnector;
import easypal.brilliard.world.brilliards.communication.CommunicationException;

/*
 * TCP is connection-oriented communication protocol, so he need a listener and a connector.
 */
public class CommunicationConnectorSocketImpl implements CommunicationConnector {
	protected String ip;
	protected int port;
	
	protected Socket socket;
	
	public CommunicationConnectorSocketImpl(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}
	@Override
	public void init() throws CommunicationException {
		/* nothing */
	}

	@Override
	public void desctroy() {
			try {
				if (socket != null) socket.close();
			} catch (IOException e) {
				/* Destruction need not regard exceptions. */
				String exceptionMessage = "Communication connection destruction fails.";
				TraceUtil.trace(this, exceptionMessage);
			} finally {
				socket = null;
			}
	}

	@Override
	public CommunicationChannel connect() throws CommunicationException {
		try {
			socket = new Socket(ip, port);
		} catch (UnknownHostException e) {
			/* Oh, there is no host corresponding to the ip address. */
			String exceptionMessage = "Communication connector don't kown the host.";
			throw new CommunicationException(exceptionMessage, e);
		} catch (IOException e) {
			/* ... */
			String exceptionMessage = "Communication connector can't create a socket.";
			throw new CommunicationException(exceptionMessage, e);
		} finally {
			/* no code */
		}
		
		return new CommunicationChannelSocketImpl(this.socket);
	}

}
